package com.atguigu.exam.service.impl;


import com.atguigu.exam.entity.Category;
import com.atguigu.exam.entity.Question;
import com.atguigu.exam.exception.ExamException;
import com.atguigu.exam.mapper.CategoryMapper;
import com.atguigu.exam.mapper.QuestionMapper;
import com.atguigu.exam.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category> implements CategoryService {

    @Autowired
    private QuestionMapper questionMapper;
    @Override
    public List<Category> getCategoryList() {
        List<Category> categoryList = baseMapper.selectList(new LambdaUpdateWrapper<Category>().orderByAsc(Category::getSort));
        addCategoryQuestionCount(categoryList);
        return categoryList;
    }


    private void addCategoryQuestionCount(List<Category> categoryList){
        List<Map<Long, Long>> categoryCount = questionMapper.getCategoryCount();
        Map<Long, Long> longMap = categoryCount.stream().collect(Collectors.toMap(
                k -> k.get("category_id"),
                v -> v.get("count")
        ));
        categoryList.forEach(category -> {
            Long l = longMap.getOrDefault(category.getId(), 0L);
            category.setCount(l);
        });

    }

    @Override
    public List<Category> getCategoryTree() {

        List<Category> categoryList = baseMapper.selectList(new LambdaQueryWrapper<Category>().orderByAsc(Category::getSort));

        addCategoryQuestionCount(categoryList);

        List<Category> fistLevelCategory = buildCategoryTree(categoryList);
        return fistLevelCategory;
    }

    @Override
    public void addCategory(Category category) {
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Category> eq = categoryLambdaQueryWrapper.eq(Category::getName, category.getName()).eq(Category::getParentId, category.getParentId());
        boolean exists = baseMapper.exists(eq);
        if(exists){
            //Category parentCategoryName = baseMapper.selectById(category.getParentId());
            throw new ExamException(444,"已经有了，你的主人王宁不让你添加");
        }
        baseMapper.insert(category);
    }

    @Override
    public void updateCategory(Category category) {
        category.setUpdateTime(null);
        LambdaUpdateWrapper<Category> categoryLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        LambdaUpdateWrapper<Category> condition = categoryLambdaUpdateWrapper.eq(Category::getName, category.getName()).eq(Category::getParentId, category.getParentId()).ne(Category::getId, category.getId());
        boolean exists = baseMapper.exists(condition);
        if(exists){
            //Category parentCategoryName = baseMapper.selectById(category.getParentId());
            throw new ExamException(444,"你的主人王宁不让你更新");
        }
        baseMapper.updateById(category);
    }

    @Override
    public void deleteCategory(Long id) {
        LambdaUpdateWrapper<Category> categoryLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        LambdaUpdateWrapper<Category> condition = categoryLambdaUpdateWrapper.eq(Category::getParentId, id);
        Long l = baseMapper.selectCount(condition);
        if(l > 0){
            throw new ExamException(444,"有儿子删不了");
        }

        LambdaUpdateWrapper<Question> questionLambdaUpdateWrapper1 = new LambdaUpdateWrapper<>();
        LambdaUpdateWrapper<Question> condition1 = questionLambdaUpdateWrapper1.eq(Question::getCategoryId, id);
        Long l1 = questionMapper.selectCount(condition1);

        if(l1 > 0){
            throw new ExamException(444,"有儿子删不了");
        }

        baseMapper.deleteById(id);
    }

    private List<Category> buildCategoryTree(List<Category> categoryList){
        Map<Long, List<Category>> categoryMap = categoryList.stream().collect(Collectors.groupingBy(Category::getParentId));
        categoryList.forEach(category -> {
            Long categoryId = category.getId();
            List<Category> childrenCategory = categoryMap.getOrDefault(categoryId, new ArrayList<>());
            category.setChildren(childrenCategory);

            long childSumCount = childrenCategory.stream().mapToLong(Category::getCount).sum();
            Long currentCount = category.getCount();
            category.setCount(currentCount+childSumCount);
        });
        List<Category> firstLevelCategory = categoryList.stream().filter(c -> c.getParentId() == 0).collect(Collectors.toList());
        return firstLevelCategory;
    }
}